//本地操作的数据存储和获取
$(function() {
	//数据初始值
//	getEMULocalStorageInit();
	//监听数据变化，存储本地数据
	addListenerEventFun();
	//手工测试的操作名字数组对象
	manualStepArray = [];
	//加载手工测试的操作名字
	getManualStep();
	//记录是否已经录制
	currentStartLuZhiBool =false;
	initSetDataArray = [{signalType:1,value:0},{signalType:22,value:500}];//开始录制时设置的初始状态值
	updateLZButtonState();
});
//获取存储的数据
function getEMULocalStorageInit(){
	for(var i = 1;i<=500;i++){
		if($('#MANIputStorageId'+i)){
			if(localStorage.getItem("MANIputStorage"+i)){
				$('#MANIputStorageId'+i).val(localStorage.getItem("MANIputStorage"+i));
			}
		}
	}
	
	if(localStorage.getItem('MANzsone')){
		if($("select[class = 'zsone']").get(0)){
			$("select[class = 'zsone']").get(0).selectedIndex = localStorage.getItem('MANzsone');
		}
	}
	if(localStorage.getItem('MANfxone')){
		if($("select[class = 'fxone']").get(0)){
			$("select[class = 'fxone']").get(0).selectedIndex = localStorage.getItem('MANfxone');
		}
	}
	if(localStorage.getItem('MANzstwo')){
		if($("select[class = 'zstwo']").get(0)){
			$("select[class = 'zstwo']").get(0).selectedIndex = localStorage.getItem('MANzstwo');
		}
	}
	if(localStorage.getItem('MANfxtwo')){
		$("select[class = 'fxtwo']").get(0).selectedIndex = localStorage.getItem('MANfxtwo');
	}
	if(localStorage.getItem('MANdengone')){
		if($("select[class = 'dengone']").get(0)){
			$("select[class = 'dengone']").get(0).selectedIndex = localStorage.getItem('MANdengone');
			dengShow('dengone');
		}
	}
	if(localStorage.getItem('MANdengtwo')){
		if($("select[class = 'dengtwo']").get(0)){
			$("select[class = 'dengtwo']").get(0).selectedIndex = localStorage.getItem('MANdengtwo');
			dengShow('dengtwo');
		}
	}
	
	for(var i = 1;i<=50;i++){
		if($(".MainCheckBoxTitle"+i)){
			if(localStorage.getItem('MainCheckBoxTitle'+i)){
				$(".MainCheckBoxTitle"+i).attr("checked",localStorage.getItem('MainCheckBoxTitle'+i));
			}
		}
	}
	
	for(var j = 1;j<15;j++){
		if($(".MANRadio"+j)){
			if(localStorage.getItem('MANRadio'+j)){
				$(".MANRadio"+j).attr("checked",localStorage.getItem('MANRadio'+j));
			}
//			var flag = localStorage.getItem('MANRadio'+j) ==="false" ? false : true;  
//			if(flag){
//				var classString = ":radio[class='MANRadio"+j+"']";
//				$(classString).prop("checked", "checked");
//			}
		}
	}
	
	//被点击的色灯按钮,如果本地有记录，则显示记录的信息
	if(localStorage.getItem('RightButtonStorage')){
		var RightButtonStorageString = localStorage.getItem('RightButtonStorage');
		var index = RightButtonStorageString.split("?")[0];
		var stateBool = RightButtonStorageString.split("?")[1];//true:色灯亮，false：色灯关闭
		var flag = stateBool ==="false" ? false : true;  
		if(flag){
			$(".rightButton button").css("border","1px solid #FFF");
			$(".RightButton"+index).css("border","1px solid rgb(38, 194, 84)");//点击的Button边框变色
			$(".RightButton button").css("color", "rgb(255, 255, 255)");//重置button字颜色为白色
			$(".RightButton"+index).css("color","rgb(38, 194, 84)");//点击的Button字变色
			setLightColor(parseInt(index),"dengs");//色灯变色
			$(".RightButton"+index).attr("data","2");
		}else{
			$(".rightButton button").css("border", "1px solid #FFF");
			$(".rightButton button").css("color", "rgb(255, 255, 255)");//重置button字颜色为白色
			$(".RightButton"+index).css("border", "1px solid yellow"); //点击的Button边框变色
			setLightColor(17, "dengs"); //色灯变色
			$(".RightButton"+index).attr("data","1");
		}
	}
}

//灯显示
function dengShow(name){
	if($(".switchInput").find(".colorLights").length!==0){//平调模式不需要变灯的颜色
		var code = $("." + name + " option:selected").attr("signalvalue");
		setLightColor(code,name);
	}	
}
//监听数据变化，存储本地数据
function addListenerEventFun(){
	$("select").on('change',function(e){
		switch (e.target.className){
			case 'zsone':
				localStorage.setItem('MANzsone', e.target.selectedIndex);
				break;
			case 'fxone':
				localStorage.setItem('MANfxone', e.target.selectedIndex);
				break;
			case 'zstwo':
				localStorage.setItem('MANzstwo', e.target.selectedIndex);
				break;
			case 'fxtwo':
				localStorage.setItem('MANfxtwo', e.target.selectedIndex);
				break;
			case 'dengone':
				localStorage.setItem('MANdengone', e.target.selectedIndex);
				break;
			case 'dengtwo':
				localStorage.setItem('MANdengtwo', e.target.selectedIndex);
				break;
			default:
				break;
		}
	});
	
	$("input").on('input',function(e)  
	{  
		if(e.target.value ==""){
			var info1 = "<div style='color:black;'>值不能为空！</div>";
			if(e.target.attributes.currentValue){
				e.target.value = e.target.attributes.currentValue.value;
			}else{
				e.target.value = 0;
			}
			warning(info1);
			return;
		}
		if(e.target.max){
			//当输入框的输入内容不在有效范围内，则提示重新输入
			if(Number(e.target.value)>Number(e.target.max) || Number(e.target.value) < Number(e.target.min)){
				var info = "<div style='color:black;'>请输入有效范围的数字:"+e.target.min+"-"+e.target.max+ "</div>";
				if(e.target.attributes.currentValue){
					e.target.value = e.target.attributes.currentValue.value;
				}else{
					e.target.value = 0;
				}
				warning(info);
		        return false;
			}
		}
		
		switch (e.target.id){
			case 'MANIputStorageId400':
				localStorage.setItem('MANIputStorage400', e.target.value);
				break;
			case 'MANIputStorageId401':
				localStorage.setItem('MANIputStorage401', e.target.value);
				break;
			case 'MANIputStorageId402':
				localStorage.setItem('MANIputStorage402', e.target.value);
				break;
			case 'MANIputStorageId403':
				localStorage.setItem('MANIputStorage403', e.target.value);
				break;
			case 'MANIputStorageId404':
				localStorage.setItem('MANIputStorage404', e.target.value);
				break;
			case 'MANIputStorageId405':
				localStorage.setItem('MANIputStorage405', e.target.value);
				break;
			case 'MANIputStorageId406':
				localStorage.setItem('MANIputStorage406', e.target.value);
				break;
			default:
				break;
		}
	}); 
	
	$(":checkbox").click(function(e){
		localStorage.setItem(e.target.className, e.target.checked);
	});
}

//根據選中的色燈顯示對應的圖片
//选择灯的类型，改变显示的图片,共三处色灯变化，复杂模式对应一二系色灯，简单模式色灯变化；code代表色灯编码，light；代码哪一处色灯变化
function setLightColor(code,light){
	var srcpath = "../../images/elements/L.png";
	    if (code==1) {srcpath = "../../images/elements/L3.png";} 
          else if (code==2) {srcpath = "../../images/elements/L2.png";}
          else if (code==3) {srcpath = "../../images/elements/L.png";}
          else if (code==4) {srcpath = "../../images/elements/LH.png";}
          else if (code==5) {srcpath = "../../images/elements/LH2.png";}
          else if (code==6) {srcpath = "../../images/elements/U.png";}
          else if (code==7) {srcpath = "../../images/elements/U2S.gif";}
          else if (code==8) {srcpath = "../../images/elements/U2.png";}
          else if (code==9) {srcpath = "../../images/elements/U3.png";}
          else if (code==10) {srcpath = "../../images/elements/UUS.gif";}
          else if (code==11) {srcpath = "../../images/elements/UU.png";}
          else if (code==12) {srcpath = "../../images/elements/HUS.gif";}
          else if (code==13) {srcpath = "../../images/elements/HU.png";}
          else if (code==14) {srcpath = "../../images/elements/HY.png";}
          else if (code==15) {srcpath = "../../images/elements/L4.png";}
          else if (code==16) {srcpath = "../../images/elements/L5.png";}
          else if (code==17) {srcpath = "../../images/elements/WZ.png";}//
          else if (code==18) {srcpath = "../../images/elements/27.9.png";}
          else if (code==19) {srcpath = "../../images/elements/H.png";}
          else if (code==20) {srcpath = "../../images/elements/B.png";}  
		 var img = $("<img src='' alt=''>");
		 if(light=="dengone"){
			 $(".semaphoresOne").empty();
			 $(".semaphoresOne").append(img);
			 $(".semaphoresOne img").attr("src", srcpath); 
		 }else if(light=="dengtwo"){
			 $(".semaphoresTwo").empty();
			 $(".semaphoresTwo").append(img);
			 $(".semaphoresTwo img").attr("src", srcpath); 
		 }
		 else if(light=="dengs"){
			 $(".dengs").empty();
			 $(".dengs").append(img);
			 $(".dengs img").attr("src", srcpath); 
		 }
 }

//state:返回的信息，type：0为失败，1位成功
//操作一次，则在操作日志中显示出来
function addSimulationManualLog(state,type,id,value){
	var content='';
	if(startLuZhiBool && !currentStartLuZhiBool){
		content = "";
		currentStartLuZhiBool = true;
	}else{
		content = "";
	}
	if(type == 1){
		content = "<div class='manualLogCell'><div class='logLeft'>"+
		getLastTime()+"</div><div class='logRight'><div><span>发送信号：</span><span>"+
		'设定参数 "'+getManualStepById(id)+'" 为 '+value+"</span></div><div><span>返回状态：</span><span class='manualLogSuc'>"+
		state+"</span></div></div></div>";
	}else{
		content = "<div class='manualLogCell'><div class='logLeft'>"+
		getLastTime()+"</div><div class='logRight'><div><span>发送信号：</span><span>"+
		'设定参数 "'+getManualStepById(id)+'" 为 '+value+"</span></div><div><span>返回状态：</span><span class='manualLogFai'>设定失败，"+
		state+"</span></div></div></div>";
	}
	//仿真测试通过websocket发送操作日字，用于广播访客看的信息；手动测试通过ajax发送操作日字，用于回放当前任务
	if(roleType == 0){
		getAllDataWebSocket.send("broadcast:"+content);
	}else if(roleType == 2){
		sendLog(content);
		$("#manualLogIframe").contents().find("#manualLogId").append(content);
		if(!$("#manualLogIframe")[0].contentWindow){
			return;
		}
		$("#manualLogIframe")[0].contentWindow.scrollWindow();
	}
}

//操作日志发送到后台
function sendLog(content){
	$.ajax({
		"url" : "../../../manualTest/addManualTestLog",
		"type" : "post",
		"data" : { 
			taskId:addManualId,
			testLog:content
		},
		"dataType" : "json",
		"success" : function(result) {
			console.log(result);
		},
		"error" : function(data) {
		}
	});
}

function addManualLogNew(str){
	if(str == undefined){
		return;
	}
	var content='';
	if(startLuZhiBool && !currentStartLuZhiBool){
		content = "";
		currentStartLuZhiBool = true;
	}else{
		content = "";
	}
	content = content+str;
	$("#manualLogIframe").contents().find("#manualLogId").append(content);
	if(!$("#manualLogIframe")[0].contentWindow){
		return;
	}
	$("#manualLogIframe")[0].contentWindow.scrollWindow();
}

//获取当前时间
function getLastTime(){
	var nowDate = new Date();     
    var year = nowDate.getFullYear();    
    var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;    
    var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();    
    var hour = nowDate.getHours()< 10 ? "0" + nowDate.getHours() : nowDate.getHours();    
    var minute = nowDate.getMinutes()< 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();    
    var second = nowDate.getSeconds()< 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();    
    return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;    
}

//通过id获取该操作的名称
function getManualStepById(id){
	var stepName = '';
	if(!manualStepArray){
		return;
	}
	for(var i = 0;i<manualStepArray.length;i++){
		if(!manualStepArray[i]['id']){
			continue;
		}
		if(id == manualStepArray[i]['id']){
			stepName = manualStepArray[i]['step'];
			break;
		}
	}
	return stepName;
}

//获取手工测试的操作名称
function getManualStep(){
	$.ajax({
        url: "../../textcommon/xml/manualLogStep.xml",
        dataType: 'xml',
        type: 'GET',
        timeout: 2000,
        error: function(xml)
        {
            alert("加载XML 文件出错！");
        },
        success: function(xml)
        {
        	manualStepArray = [];
            $(xml).find("step").each(function(i)
            {
            	var id = $(this).attr("id");
            	var step = $(this).children("content").text();
            	manualStepArray.push({id:id,step:step});
            });
        }
    });
}

//特殊的按钮点击的录制处理
function guojiFun(destination, signalType){
	var content='';
	if(destination == 1 && signalType == 43){
		content = "Ⅰ系 过机 点击 ";
	}
	if(destination == 2 && signalType == 43){
		content = "Ⅱ系 过机 点击";
	}
	if(destination == 3 && signalType == 43){
		content = "点击";
	}
	return content;
}

//添加数据到设置参数的数组中
function changeInitData(type,value){
	var bool = false;
	for(var i = 0;i<initSetDataArray.length;i++){
		if(initSetDataArray[i].signalType ==type){
			bool = true;
			initSetDataArray[i].value = value;
			break;
		}
	}
	
	if(!bool){
		initSetDataArray.push({signalType:type,value:value});
	}
}
//更新操作按钮的状态
//1、当未设置跟踪点时，开始录制、开始观测、停止观测和停止录制按钮都不能点击
//2、当设置跟踪点完成时，录制按钮可以点击，开始观测、停止观测和停止录制按钮都不能点击
//3、当录制按钮点击后，开始观测和停止录制按钮可以点击,停止观测按钮不可点击
//4、当点击开始观测按钮后，停止观测按钮可以点击，开始观测按钮不可点击，
//5、当点击停止观测按钮后，开始观测按钮可以点击，
//6、当点击停止录制时，录制按钮可以点击，开始观测和停止观测按钮不可点击
function updateLZButtonState(){
	$('#luzhiId').removeClass('luzhiBtnCell');
	$('#luzhiId').addClass('luzhiBtn');
	$('#startGC').removeClass('luzhiBtnCell');
	$('#startGC').addClass('luzhiBtn');
	$('#endGC').removeClass('luzhiBtnCell');
	$('#endGC').addClass('luzhiBtn');
	$('#stopLuZhiBtn').removeClass('luzhiBtnCell');
	$('#stopLuZhiBtn').addClass('luzhiBtn');
	if(!setGGBool){
		$('#luzhiId').attr('disabled',true);
		$('#startGC').attr('disabled',true);
		$('#endGC').attr('disabled',true);
		$('#stopLuZhiBtn').attr('disabled',true);
	}else{
		if(!startLuZhiBool){
			$('#luzhiId').attr('disabled',false);
			$('#startGC').attr('disabled',true);
			$('#endGC').attr('disabled',true);
			$('#stopLuZhiBtn').attr('disabled',true);
			$('#luzhiId').removeClass('luzhiBtn');
			$('#luzhiId').addClass('luzhiBtnCell');
		}else{
			if(!startGCBool){
				$('#startGC').attr('disabled',false);
				$('#endGC').attr('disabled',true);
				$('#startGC').removeClass('luzhiBtn');
				$('#startGC').addClass('luzhiBtnCell');
			}else{
				$('#startGC').attr('disabled',true);
				$('#endGC').attr('disabled',false);
				$('#endGC').removeClass('luzhiBtn');
				$('#endGC').addClass('luzhiBtnCell');
			}
			$('#luzhiId').attr('disabled',true);
			$('#stopLuZhiBtn').attr('disabled',false);
			$('#stopLuZhiBtn').removeClass('luzhiBtn');
			$('#stopLuZhiBtn').addClass('luzhiBtnCell');
		}
	}
}
